package machine

import (
	"CaptchaCluster/log"
	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/mem"
	"sync"
	"time"
)

type MachineInfo struct {
	mutex sync.Mutex

	CPUKernel  int
	CPUPercent float64
	MemPercent float64
}

var Instance = new(MachineInfo)

func Init() {
	wait := new(sync.WaitGroup)
	wait.Add(1)

	go func() {
		for {
			cpuInfo, err := cpu.Percent(1*time.Second, true)
			if err != nil {
				log.Fatal("读取CPU占用率失败:%v", err)
			}

			memInfo, err := mem.VirtualMemory()
			if err != nil {
				log.Fatal("读取内存占用率失败:%v", err)
			}

			Instance.mutex.Lock()

			Instance.CPUKernel = len(cpuInfo)
			var sum float64
			for _, v := range cpuInfo {
				sum += v
			}
			Instance.CPUPercent = sum

			Instance.MemPercent = memInfo.UsedPercent

			Instance.mutex.Unlock()

			cpuInfo = nil
			memInfo = nil

			if wait != nil {
				wait.Done()
			}
			time.Sleep(1 * time.Second)
		}
	}()
	wait.Wait()
	wait = nil
}
